<template>
  <view class="normal-login-container">

    <view class="logo-content align-center justify-center flex">
      <image
          style="width: 300rpx; height: 150rpx"
          :src="globalConfig.appInfo.logo"
          mode="widthFix"
      >
      </image>
      <view class="login-form-content">
        <view class="action-btn">
          <button
              @click="handleLogin"
              class="login-btn cu-btn block bg-blue lg round"
          >
            {{ bindWechat ? '微信一键绑定' : '微信一键登录' }}
          </button>
        </view>
      </view>
      <view class="agree text-center">
        <view class="radio" v-if="!radiovalue" @click="changeState"></view>
        <view class="radio-checked" v-else @click="changeState">
          <u-icon name="checkbox-mark" color="#fff" size="10px"></u-icon>
        </view>
            <text class="text-grey1">{{ bindWechat ? '绑定' : '登录' }}即代表同意</text>
            <text @click="handleUserAgreement" class="text-red">《用户协议》</text>
            <text @click="handlePrivacy" class="text-red">《隐私协议》</text>



      </view>
      <u-modal :show="showModal"  :content='content' @confirm="confirmModal"></u-modal>
    </view>

    <view class="other-login" v-if="!bindWechat">
      <text class="text-grey1" v-show="showBottom">————其他登录方式————</text>
      <image
          src="../static/images/login/phone.png"
          mode="scaleToFill"
          class="login-img"
          @click="handlePhoneLogin"
          v-show="showBottom"
      />
    </view>


  </view>
</template>

<script>
import {getCodeImg} from "@/api/login";
import {getStorage, setStorage} from "@/utils/auth";
import application from "@/static/const/application";
import {getWxUrlParam, isEmptyString} from "@/utils/common";

export default {
  data() {
    return {
      codeUrl: "",
      codeWechat: "", //微信code
      captchaEnabled: true,
      globalConfig: getApp().globalData.config,
      loginForm: {
        username: "admin",
        password: "admin123",
        code: "",
        uuid: "",
      },
      avatarUrl: "", //微信头像
      name: "", //微信昵称
      bindWechat: false, //是否绑定微信
      user: {},
      inviteId: "",
      showBottom: true,
      radiovalue: false,
      showModal: false,
      content: "请先同意《用户协议》和《隐私协议》",
    };
  },
  onLoad(params) {
    if (params.state === 'bindWechat') {
      this.bindWechat = true
      uni.setNavigationBarTitle({
        title: '绑定微信'
      });
      this.user = getStorage(application.user)
    }
    if (!isEmptyString(params.q)) {
      const qrUrl = decodeURIComponent(params.q)
      //此处就是我们要获取的参数 json，通过方法解析
      let jsonUrl = getWxUrlParam(qrUrl);
      //比如我要得到id的值，直接取值即可
      let id = jsonUrl.invitationId;
      this.inviteId = id;
      this.showBottom = false;
    }
    if(!isEmptyString(params.invitationId)){
      this.inviteId = params.invitationId;
      this.showBottom = false;
    }
  },
  methods: {
    // 隐私协议
    handlePrivacy() {
      let site = this.globalConfig.appInfo.agreements[0];
      this.$tab.navigateTo(
          `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      );
    },
    // 用户协议
    handleUserAgreement() {
      let site = this.globalConfig.appInfo.agreements[1];
      this.$tab.navigateTo(
          `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      );
    },
    // 获取图形验证码
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
            res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    // 登录方法
    async handleLogin() {
      if (!this.radiovalue) {
        this.showModal = true;
        return;
      }
      this.$modal.loading("登录中，请耐心等待...");
      if (!this.bindWechat) {
        this.weChatLogin();
      } else {
        this.bindWechatLogin();
      }

    },
    // 密码登录
    async pwdLogin() {
      this.$store
          .dispatch("Login", this.loginForm)
          .then(() => {
            this.$modal.closeLoading();
            this.loginSuccess();
          })
          .catch(() => {
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
    },
    // 微信登录
    weChatLogin() {
      const that = this;
      uni.getUserProfile({
        desc: "获取你的昵称、头像、地区及性别",
        success: (res) => {
          that.avatarUrl = res.userInfo.avatarUrl;
          that.name = res.userInfo.nickName;
          uni.login({
            provider: "weixin", //使用微信登录
            onlyAuthorize: true,
            success: function (loginRes) {
              that.codeWechat = loginRes.code;
              //将这些上传到wxLogin接口
              let params= {
                code: that.codeWechat,
                headPortrait: that.avatarUrl,
                name: that.name,
              };
              if(!isEmptyString(that.inviteId)){
                params.invitationId = that.inviteId
              }
              that.$store
                  .dispatch("WxLogin", params)
                  .then(() => {
                    that.$modal.closeLoading();
                    that.loginSuccess();
                  });
            },
          });
        },
        fail() {
        },
      });
    },
    // 绑定微信
    bindWechatLogin() {
      const that = this;
      uni.getUserProfile({
        desc: "获取你的昵称、头像、地区及性别",
        success: (res) => {
          console.log(res);
          that.avatarUrl = res.userInfo.avatarUrl;
          that.name = res.userInfo.nickName;
          uni.login({
            provider: "weixin", //使用微信登录
            onlyAuthorize: true,
            success: function (loginRes) {
              that.codeWechat = loginRes.code;
              console.log(that.codeWechat);
              //将这些上传到wxLogin接口
              that.$store
                  .dispatch("EditUser", {
                    code: that.codeWechat,
                    userId: that.user.userId,
                    name: that.name,
                  })
                  .then(() => {
                    console.log("绑定成功");
                    that.$modal.closeLoading();
                    that.bindSuccess();
                  });
            },
          });
        },
        fail() {
        },
      });
    },
    // 登录成功后，处理函数
    loginSuccess() {
      // 设置用户信息
      this.$store.dispatch("GetInfo").then(() => {
        this.$tab.reLaunch("/pages/index");
      });
    },
    // 手机号登录
    handlePhoneLogin() {
        uni.reLaunch({
          url: "/pages/login-phone",
        });
    },
    // 绑定成功后，处理函数
    bindSuccess() {
      // 设置用户信息
      this.$store.dispatch("GetUserInfoByUserId", this.user.userId).then((res) => {
        setStorage(application.user, res.data);
        uni.$emit("bindWechatSuccess");
        uni.navigateBack({
          delta: 1
        });
      });
    },
    //勾选协议
    changeState() {
      this.radiovalue = !this.radiovalue;
    },
    confirmModal() {
      this.showModal = false;
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #ffffff;
}

.normal-login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  background: url(../static/images/login/建筑.png) no-repeat center bottom;
  background-size: contain;
  background-position-x: -10%;

  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: url(../static/images/login/云朵.png) no-repeat center center;
    background-size: cover;

    image {
      border-radius: 4px;
    }

    .title {
      margin-top: 10px;
      margin-left: 10px;
      font-size: 36 rpx;
    }
  }

  .login-form-content {
    text-align: center;
    margin: 20px auto 0;
    width: 80%;
    .login-btn {
      margin-top: 40px;
      height: 45px;
      border-radius: 10px;
      background-color: $uni-color-button;
    }
  }

  .easyinput {
    width: 100%;
  }
}

.login-code-img {
  height: 45px;
}

.other-login {
  width: 100%;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .margin10 {
    margin-top: 20%;
  }
}

.agree {
  color: #333;
  margin-top: 20px;
  font-size: 0.7rem;
  width: 80%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-img {
  width: 3rem;
  height: 3rem;
  margin-top: 0.5rem;
}
.radio {
  width: 30rpx;
  height: 30rpx;
  border-radius: 50%;
  border: 1px solid #999;
  margin-right: 10rpx;
}
.radio-checked {
  width: 30rpx;
  height: 30rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e43d33;
  margin-right: 10rpx;
}
</style>
